﻿using System;
using System.Reflection;
using SwinGame;
using System.Runtime.InteropServices;
using Color = System.Drawing.Color;

namespace SimpleSurvival.src
{
    //-----------------------------------------------//
    //CLASS - CORE.cs
    //-----------------------------------------------//
    public static class CORE
    {
        //Fast way to do sqrt//
        //http://blog.wouldbetheologian.com/2011/11/fast-approximate-sqrt-method-in-c.html
        [StructLayout(LayoutKind.Explicit)]
        private struct FloatIntUnion
        {
            [FieldOffset(0)]
            public float f;

            [FieldOffset(0)]
            public int tmp;
        }
        public static float Sqrt(float z)
        {
            if (z == 0) return 0;
            FloatIntUnion u;
            u.tmp = 0;
            u.f = z;
            u.tmp -= 1 << 23; /* Subtract 2^m. */
            u.tmp >>= 1; /* Divide by 2. */
            u.tmp += 1 << 29; /* Add ((b + 1) / 2) * 2^m. */
            return u.f;
        }

        public static Vector NormaliseVector(Vector a)
        {
            float d2 = GetDist2(new Vector { X = 0, Y = 0 }, a);//optimise
            if (d2 == 0.0f) { throw new Exception("Divide by 0"); }
            float d = Sqrt(d2);
            a.X /= d2;
            a.Y /= d2;
            return a;
        }

        public static Vector GetDirectionalVector(Vector a, Vector b)
        {
            float dx = a.X - b.X;
            float dy = a.Y - b.Y;
            float d2 = dx * dx + dy * dy;
            d2 = Sqrt(d2);
            dx /= d2;
            dy /= d2;
            return new Vector { X = dx, Y = dy };
        }

        public static float GetDist2(Vector a, Vector b)
        {
            return (a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y);
        }
    }
}
